package com.yc.litemonitoring.client;

import com.yc.util.CommandLineArgs;
import com.yc.util.CommandLineArgsParser;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;



public class LiteMonitoringClient {
    private static final String CMD_PORT = "port";
    private static final String CMD_SERVER = "server";
    private static final int DEFUALT_PORT = 8083;
    private static final String DEFUALT_SERVER = "localhost";

    public static void main(String[] args) throws Exception {
        CommandLineArgs commandLineArgs = CommandLineArgsParser.parse(args);
        Integer port = commandLineArgs.getIntArg(CMD_PORT);
        String server = commandLineArgs.getArg(CMD_SERVER);

        if (port == null) {
            port = DEFUALT_PORT;
        }

        if (server == null) {
            server = DEFUALT_SERVER;
        }

        new LiteMonitoringClient(server, port).run();
    }

    private final String host;
    private final int port;

    public LiteMonitoringClient(String host, int port){
        this.host = host;
        this.port = port;
    }

    public void run() throws Exception{
        // 配置客户端NIO线程组
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            // 客户端启动器
            Bootstrap bootstrap  = new Bootstrap()
                    .group(group) // 线程组
                    .channel(NioSocketChannel.class) // 客户端通道的实现类
                    .handler(new LiteMonitoringClientInitializer());  // 客户端通道的处理器

            Channel channel = bootstrap.connect(host, port).sync().channel();

            // 等待连接关闭
            channel.closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            group.shutdownGracefully();
        }

    }

}
